<template>
  <el-container class="admin-layout">
    <el-main>
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>订单管理</span>
            <el-button type="primary" @click="handleOpenDialog()">添加订单</el-button>
          </div>
        </template>

        <div class="filter-container">
          <el-input
            v-model="searchQuery"
            placeholder="按顾客或商品ID搜索"
            clearable
            style="width: 300px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <el-table
          :data="filteredOrders"
          v-loading="loading"
          style="width: 100%"
          row-key="id"
          @expand-change="handleExpand"
        >
          <el-table-column type="expand">
            <template #default="props">
              <div v-if="expandLoadingMap[props.row.id]" style="padding: 20px; text-align:center;">
                <el-spin />
              </div>
              <template v-else>
                <el-descriptions title="用户信息" size="small" :column="2" border>
                  <el-descriptions-item label="昵称">{{ detailMap[props.row.id]?.user.name }}</el-descriptions-item>
                  <el-descriptions-item label="手机号">{{ detailMap[props.row.id]?.user.phoneNumber }}</el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="商品信息" size="small" :column="2" border style="margin-top: 10px;">
                  <el-descriptions-item label="名称">{{ detailMap[props.row.id]?.product.name }}</el-descriptions-item>
                  <el-descriptions-item label="价格">¥{{ detailMap[props.row.id]?.product.price?.toFixed(2) }}</el-descriptions-item>
                </el-descriptions>
                <el-descriptions title="地址信息" size="small" :column="2" border style="margin-top: 10px;">
                  <el-descriptions-item label="收件人">{{ detailMap[props.row.id]?.address.receiverName }}</el-descriptions-item>
                  <el-descriptions-item label="电话">{{ detailMap[props.row.id]?.address.receiverPhone }}</el-descriptions-item>
                  <el-descriptions-item label="完整地址" :span="2">
                    {{ detailMap[props.row.id]?.address.country }} {{ detailMap[props.row.id]?.address.province }} {{ detailMap[props.row.id]?.address.county }} {{ detailMap[props.row.id]?.address.detailAddress }}
                  </el-descriptions-item>
                </el-descriptions>
              </template>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="订单 ID" key="id" />
          <el-table-column prop="customerId" label="顾客 ID" key="customerId" />
          <el-table-column prop="productId" label="商品 ID" key="productId" />
          <el-table-column prop="addressId" label="地址 ID" key="addressId" />
          <el-table-column prop="status" label="状态" key="status">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'end' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="总金额" key="totalAmount" />
          <el-table-column label="下单日期" key="orderDate" width="180">
            <template #default="scope">
              {{ formatDateToCN(scope.row.orderDate) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" key="actions">
            <template #default="scope">
              <el-button size="small" @click="handleOpenDialog(scope.row)">编辑</el-button>
              <el-popconfirm
                title="确定要删除这个订单吗?"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="handleDelete(scope.row.id)"
              >
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

      </el-card>
    </el-main>
  </el-container>

  <!-- Add/Edit Dialog -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="resetForm">
    <el-form :model="formOrder" label-width="100px" ref="formRef" :rules="rules">
      <el-form-item label="顾客" prop="customerId">
        <el-select v-model="formOrder.customerId" placeholder="请选择顾客" filterable style="width: 100%;">
          <el-option v-for="u in allCustomers" :key="u.id" :label="`${u.name}(${u.phoneNumber})`" :value="u.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="地址" prop="addressId">
        <el-select v-model="formOrder.addressId" placeholder="请选择地址" :disabled="!formOrder.customerId" filterable style="width: 100%;">
          <el-option v-for="addr in userAddresses" :key="addr.id" :label="`${addr.country}${addr.province}${addr.county}${addr.detailAddress}`" :value="addr.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品" prop="productId">
        <el-select v-model="formOrder.productId" placeholder="请选择商品" filterable style="width: 100%;">
          <el-option v-for="p in allProducts" :key="p.id" :label="p.name" :value="p.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="小计金额" prop="subtotalAmount">
        <el-input-number v-model="formOrder.subtotalAmount" :precision="2" :min="0" controls-position="right" style="width: 100%;" />
      </el-form-item>
       <el-form-item label="运费" prop="shippingFee">
        <el-input-number v-model="formOrder.shippingFee" :precision="2" :min="0" controls-position="right" style="width: 100%;" />
      </el-form-item>
       <el-form-item label="折扣金额" prop="discountAmount">
        <el-input-number v-model="formOrder.discountAmount" :precision="2" :min="0" controls-position="right" style="width: 100%;" />
      </el-form-item>
       <el-form-item label="总金额" prop="totalAmount">
        <el-input-number v-model="formOrder.totalAmount" :precision="2" :min="0" controls-position="right" style="width: 100%;" />
      </el-form-item>
      <el-form-item v-if="editingOrderId" label="订单状态" prop="status">
        <el-select v-model="formOrder.status" placeholder="选择状态" style="width: 100%;">
          <el-option label="shipped" value="shipped" />
          <el-option label="end" value="end" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive, watch } from 'vue';
import apiClient from '../../axios/axios';
import { ElMessage, ElIcon } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';

interface Order {
  id: number;
  customerId: number;
  productId: number;
  addressId: number;
  status: string;
  subtotalAmount: number;
  shippingFee: number;
  discountAmount: number;
  totalAmount: number;
  orderDate: string;
}

interface User { id:number; name:string; phoneNumber:string; }
interface Product { id:number; name:string; price:number; }
interface Address { id:number; receiverName:string; receiverPhone:string; country:string; province:string; county:string; detailAddress:string; }

// Omitting id and orderDate for the form
type OrderForm = Omit<Order, 'id' | 'orderDate'>;

const allOrders = ref<Order[]>([]);
const loading = ref(false);
const searchQuery = ref('');

const formatDateToCN = (iso: string) => {
  if (!iso) return '';
  const date = new Date(iso);
  return date.toLocaleString('zh-CN', {
    hour12: false,
    timeZone: 'Asia/Shanghai',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

const filteredOrders = computed(() => {
  if (!searchQuery.value) {
    return allOrders.value;
  }
  const query = searchQuery.value.toLowerCase();
  return allOrders.value.filter(order =>
    String(order.customerId).toLowerCase().includes(query) ||
    String(order.productId).toLowerCase().includes(query)
  );
});

const fetchOrders = async () => {
  loading.value = true;
  try {
    const response = await apiClient.get<Order[]>('/orders');
    allOrders.value = response.data;
  } catch (error) {
    console.error("Failed to fetch orders", error);
    ElMessage.error('获取订单列表失败');
  } finally {
    loading.value = false;
  }
};

// --- Dialog and Form State ---
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref<FormInstance>();
const editingOrderId = ref<number | null>(null);

const initialFormOrderState: OrderForm = {
  customerId: 1,
  productId: 1,
  addressId: 1,
  status: 'shipped',
  subtotalAmount: 0,
  shippingFee: 0,
  discountAmount: 0,
  totalAmount: 0,
};

const formOrder = reactive<OrderForm>({ ...initialFormOrderState });

const rules = reactive<FormRules>({
    customerId: [{ required: true, message: '请输入顾客 ID', trigger: 'blur' }],
    productId: [{ required: true, message: '请输入商品 ID', trigger: 'blur' }],
    addressId: [{ required: true, message: '请输入地址 ID', trigger: 'blur' }],
    subtotalAmount: [{ required: true, message: '请输入小计金额', trigger: 'blur' }],
    shippingFee: [{ required: true, message: '请输入运费', trigger: 'blur' }],
    discountAmount: [{ required: true, message: '请输入折扣金额', trigger: 'blur' }],
    totalAmount: [{ required: true, message: '请输入总金额', trigger: 'blur' }],
});

const resetForm = () => {
  Object.assign(formOrder, initialFormOrderState);
  editingOrderId.value = null;
  formRef.value?.clearValidate();
};

// data lists for selects
const allCustomers = ref<User[]>([]);
const allProducts = ref<Product[]>([]);
const userAddresses = ref<Address[]>([]);

const fetchCustomersAndProducts = async () => {
  try {
    const [usersRes, productsRes] = await Promise.all([
      apiClient.get<User[]>('/user'),
      apiClient.get<Product[]>('/product'),
    ]);
    allCustomers.value = usersRes.data;
    allProducts.value = productsRes.data;
  } catch (err) {
    console.error('fetch users/products failed', err);
    ElMessage.error('获取顾客或商品列表失败');
  }
};

const loadAddresses = async (userId: number | null) => {
  if (!userId) {
    userAddresses.value = [];
    formOrder.addressId = null as any;
    return;
  }
  try {
    const res = await apiClient.get<Address[]>(`/address/user/${userId}`);
    userAddresses.value = res.data;
    if (!userAddresses.value.find(a => a.id === formOrder.addressId)) {
      formOrder.addressId = null as any;
    }
  } catch (err) {
    console.error('fetch addresses failed', err);
    ElMessage.error('获取地址失败');
  }
};

watch(() => formOrder.customerId, (newId) => {
  loadAddresses(newId);
});

const handleOpenDialog = (order?: Order) => {
  if (order) {
    dialogTitle.value = '编辑订单';
    editingOrderId.value = order.id;
    const { id, orderDate, ...formData } = order;
    Object.assign(formOrder, formData);
    loadAddresses(order.customerId);
  } else {
    dialogTitle.value = '添加订单';
    resetForm();
    // 若已有顾客列表，自动选择第一个顾客并加载地址
    if (allCustomers.value.length) {
      formOrder.customerId = allCustomers.value[0].id;
      loadAddresses(formOrder.customerId);
    } else {
      loadAddresses(null);
    }
  }
  dialogVisible.value = true;
};

const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        // Exclude status when creating, as it's read-only on creation
        const payload = { ...formOrder };
        if (!editingOrderId.value) {
           const {status, ...creationPayload} = payload;
            await apiClient.post('/orders', creationPayload);
        } else {
            await apiClient.put(`/orders/${editingOrderId.value}`, payload);
        }
        ElMessage.success(editingOrderId.value ? '订单更新成功' : '订单添加成功');
        dialogVisible.value = false;
        fetchOrders();
      } catch (error) {
        console.error('Failed to save order', error);
        ElMessage.error(editingOrderId.value ? '更新订单失败' : '添加订单失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

const handleDelete = async (orderId: number) => {
  loading.value = true;
  try {
    await apiClient.delete(`/orders/${orderId}`);
    ElMessage.success('订单删除成功');
    await fetchOrders();
  } catch (error) {
    console.error('Failed to delete order', error);
    ElMessage.error('删除订单失败');
  } finally {
    loading.value = false;
  }
};

const expandLoadingMap = ref<Record<number, boolean>>({});
const detailMap = ref<Record<number, { user: User; product: Product; address: Address }>>({});

const handleExpand = async (row: Order, expandedRows: Order[]) => {
  if (!expandedRows.includes(row)) return; // 仅在展开时处理
  if (detailMap.value[row.id]) return; // 已有缓存
  expandLoadingMap.value[row.id] = true;
  try {
    const [userRes, productRes, addressRes] = await Promise.all([
      apiClient.get<User>(`/user/${row.customerId}`),
      apiClient.get<Product>(`/product/${row.productId}`),
      apiClient.get<Address>(`/address/${row.addressId}`),
    ]);
    detailMap.value[row.id] = {
      user: userRes.data,
      product: productRes.data,
      address: addressRes.data,
    };
  } catch (err) {
    console.error('展开信息获取失败', err);
    ElMessage.error('获取订单详情失败');
  } finally {
    expandLoadingMap.value[row.id] = false;
  }
};

onMounted(() => {
  fetchOrders();
  fetchCustomersAndProducts();
});
</script>

<style scoped>
.admin-layout {
  height: 100%;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.filter-container {
  margin-bottom: 20px;
}
</style>
